package com.atguigu.gulimall.ware.lisener;

import com.atguigu.common.to.mq.StockItemTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
@RabbitListener( queues = "stock.release.stock.queue")
public class StockLisener {


     @Autowired
     WareSkuService wareSkuService;

    @RabbitHandler
    public void handleReleaseStock(StockItemTo stockItemTo, Message message, Channel channel) throws RuntimeException, IOException {
         try{
             wareSkuService.handleReleaseStock(stockItemTo);
             channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
         }catch(Exception e){
              // 处理消息 发生异常 把信息重入队列
             channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }


    /**
     *   在 关闭订单后  立马处理解锁库存
     * @param orderSn
     * @param message
     * @param channel
     * @throws IOException
     */
   @RabbitHandler
   public void handleReleaseAfterOrder(String orderSn,Message message, Channel channel) throws IOException {
       try{
           wareSkuService.handleReleaseAfterOrder(orderSn);
           channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
       }catch(Exception e){
           // 处理消息 发生异常 把信息重入队列
           channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
       }
   }


}
